﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
	Layout = null;
}
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>职级管理</title>
	<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
	<style>
		.search-box {
			padding: 15px;
			background: #fff;
			margin-bottom: 15px;
		}
		.action-buttons {
			padding: 10px 0;
		}
		.layui-btn-group {
			margin-right: 10px;
		}
		.layui-form-label {
			width: auto;
			padding: 9px 0;
		}
		.layui-input-inline {
			margin-right: 10px;
		}
		.salary-range-separator {
			float: left;
			margin: 0 5px;
			line-height: 38px;
		}
		.table-container {
			padding: 0 15px;
		}
		.layui-table {
			margin-top: 0;
		}
		.pagination-container {
			text-align: right;
			padding: 10px 15px;
		}
	</style>
</head>
<body>
	@Html.AntiForgeryToken()
	<!-- 搜索区域 -->
	<div class="search-box">
		<form class="layui-form" action="">
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">职级编码</label>
					<div class="layui-input-inline">
						<input type="text" name="jobGradeCoding" placeholder="请输入职级编码" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-inline">
					<label class="layui-form-label">职级层次</label>
					<div class="layui-input-inline">
						<input type="text" name="jobGradeLevel" placeholder="请输入职级层次" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-inline">
					<label class="layui-form-label">职级层次名称</label>
					<div class="layui-input-inline">
						<input type="text" name="jobGradeLevelName" placeholder="请输入职级层次名称" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-inline">
					<label class="layui-form-label">薪资范围</label>
					<div class="layui-input-inline" style="width: 100px;">
						<input type="number" name="salaryRangelower" placeholder="下限" autocomplete="off" class="layui-input">
					</div>
					<div class="salary-range-separator">~</div>
					<div class="layui-input-inline" style="width: 100px;">
						<input type="number" name="salaryRangelimits" placeholder="上限" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-inline">
					<button class="layui-btn" lay-submit lay-filter="searchForm">
						<i class="layui-icon layui-icon-search"></i> 搜索
					</button>
					<button type="reset" class="layui-btn layui-btn-primary">
						<i class="layui-icon layui-icon-refresh"></i> 重置
					</button>
				</div>
			</div>
		</form>
	</div>

	<!-- 操作按钮区域 -->
	<div class="action-buttons">
		<div class="layui-btn-group">
			<button class="layui-btn layui-btn-normal" id="addJobGradeBtn">
				<i class="layui-icon layui-icon-add-1"></i> 新增
			</button>
			<button class="layui-btn layui-btn-warm" id="editBatchBtn">
				<i class="layui-icon layui-icon-edit"></i> 修改
			</button>
			<button class="layui-btn layui-btn-danger" id="deleteBatchBtn">
				<i class="layui-icon layui-icon-delete"></i> 删除
			</button>
			<button class="layui-btn" id="exportBtn">
				<i class="layui-icon layui-icon-export"></i> 导出
			</button>
		</div>
	</div>

	<!-- 表格区域 -->
	<div class="table-container">
		<table class="layui-table" lay-even lay-skin="line">
			<thead>
				<tr>
					<th style="width: 48px;"><input type="checkbox" name="select-all" lay-filter="select-all" lay-skin="primary" title=" "></th>
					<th>职级编码</th>
					<th>职级层次</th>
					<th>职级层次名称</th>
					<th colspan="2" style="text-align: center;">薪资范围(元)</th>
					<th>备注</th>
					<th>操作</th>
				</tr>
				<tr>
					<th></th>
					<th></th>
					<th></th>
					<th></th>
					<th>薪资范围下限</th>
					<th>薪资范围上限</th>
					<th></th>
					<th></th>
				</tr>
			</thead>
			<tbody id="jobGradeTable"></tbody>
		</table>
	</div>

	<!-- 分页区域 -->
	<div class="pagination-container" id="pagination"></div>

	<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
	<script>
		var form;
		var layer;
		var laypage;
		var $;

		layui.use(['form', 'layer', 'laypage'], function(){
			form = layui.form;
			layer = layui.layer;
			laypage = layui.laypage;
			$ = layui.$;

			// 初始化加载数据
			loadData();

			// 搜索表单提交
			form.on('submit(searchForm)', function(data) {
				console.log('搜索参数:', data.field); // 添加日志
				loadData(1, data.field);
				return false;
			});

			// 重置按钮点击事件
			$('button[type="reset"]').click(function() {
				// 清空表单
				$('input[name="jobGradeCoding"]').val('');
				$('input[name="jobGradeLevel"]').val('');
				$('input[name="jobGradeLevelName"]').val('');
				$('input[name="salaryRangelower"]').val('');
				$('input[name="salaryRangelimits"]').val('');
				
				// 重新加载数据
				loadData(1);
				
				return false;
			});

			// 监听全选框
			form.on('checkbox(select-all)', function(data){
				var checked = this.checked;
				$('input[name="select-item"]').each(function(){
					this.checked = checked;
				});
				form.render('checkbox');
			});

			// 监听单选框
			form.on('checkbox(select-item)', function(data){
				var isAll = true;
				$('input[name="select-item"]').each(function(){
					if(!this.checked) isAll = false;
				});
				$('input[name="select-all"]').prop('checked', isAll);
				form.render('checkbox');
			});

			// 新增按钮点击事件
			$('#addJobGradeBtn').on('click', function() {
				layer.open({
					type: 2,
					title: '添加职级',
					area: ['600px', '500px'],
					content: '/JobGradeManagement/AddJobGrade',
					end: function() {
						loadData(1);
					}
				});
			});

			// 批量删除按钮点击事件
			$('#deleteBatchBtn').on('click', function() {
				var checkedIds = getSelectedIds();

				if (checkedIds.length === 0) {
					layer.msg('请选择要删除的记录', {icon: 2});
					return;
				}

				layer.confirm('确定要删除选中的' + checkedIds.length + '条记录吗？', {
					icon: 3,
					title: '提示',
					btn: ['确定', '取消']
				}, function(index) {
					deleteJobGrades(checkedIds);
					layer.close(index);
				});
			});

			// 导出按钮点击事件
			$('#exportBtn').on('click', function() {
				// 获取当前的搜索参数
				var searchParams = {
					jobGradeCoding: $('input[name="jobGradeCoding"]').val(),
					jobGradeLevel: $('input[name="jobGradeLevel"]').val(),
					jobGradeLevelName: $('input[name="jobGradeLevelName"]').val(),
					salaryRangelower: $('input[name="salaryRangelower"]').val(),
					salaryRangelimits: $('input[name="salaryRangelimits"]').val()
				};

				// 构建URL和查询参数
				var url = '/JobGradeManagement/ExportJobGrades';
				var queryString = Object.keys(searchParams)
					.filter(key => searchParams[key]) // 只包含有值的参数
					.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(searchParams[key]))
					.join('&');

				if (queryString) {
					url += '?' + queryString;
				}

				// 使用window.location.href下载文件
				window.location.href = url;
			});
		});

		// 加载数据
		function loadData(page = 1, searchParams = {}) {
			var loadingIndex = layer.load(1, {
				shade: [0.3, '#fff']
			});

			// 获取表单数据
			var queryParams = {
				page: page,
				limit: 10
			};

			// 只有当值不为空时才添加到查询参数中
			if (searchParams.jobGradeCoding) {
				queryParams.jobGradeCoding = searchParams.jobGradeCoding;
			}
			if (searchParams.jobGradeLevel) {
				queryParams.jobGradeLevel = searchParams.jobGradeLevel;
			}
			if (searchParams.jobGradeLevelName) {
				queryParams.jobGradeLevelName = searchParams.jobGradeLevelName;
			}
			if (searchParams.salaryRangelower) {
				queryParams.salaryRangelower = parseInt(searchParams.salaryRangelower);
			}
			if (searchParams.salaryRangelimits) {
				queryParams.salaryRangelimits = parseInt(searchParams.salaryRangelimits);
			}

			// 添加调试日志
			console.log('最终查询参数:', queryParams);

			$.ajax({
				url: "/JobGradeManagement/GetJobGrades",
				type: "GET",
				data: queryParams,
				success: function(res) {
					layer.close(loadingIndex);
					console.log('服务器响应:', res); // 添加响应日志
					if (res && res.items) {
						renderTable(res.items);
						renderPagination(res.totalCount);
					} else if (res && Array.isArray(res)) {
						renderTable(res);
						renderPagination(res.length);
					} else {
						layer.msg('获取数据失败：返回格式错误', {icon: 2});
					}
				},
				error: function(xhr) {
					layer.close(loadingIndex);
					console.error('请求错误:', xhr); // 添加错误日志
					var errorMsg = '获取数据失败';
					if (xhr.responseJSON && xhr.responseJSON.message) {
						errorMsg = xhr.responseJSON.message;
					}
					layer.msg(errorMsg, {icon: 2});
				}
			});
		}

		// 渲染表格
		function renderTable(data) {
			var html = '';
			if (data && data.length > 0) {
				data.forEach(function(item) {
					html += `
						<tr>
							<td><input type="checkbox" name="select-item" lay-filter="select-item" lay-skin="primary" title=" " value="${item.id}"></td>
							<td>${item.jobGradeCoding || ''}</td>
							<td>${item.jobGradeLevel || ''}</td>
							<td>${item.jobGradeLevelName || ''}</td>
							<td>${item.salaryRangelower || 0}</td>
							<td>${item.salaryRangelimits || 0}</td>
							<td>${item.referenceColumn || ''}</td>
							<td>
								<button class="layui-btn layui-btn-xs" onclick="editJobGrade(${item.id})">
									<i class="layui-icon layui-icon-edit"></i>修改
								</button>
								<button class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteJobGrade(${item.id})">
									<i class="layui-icon layui-icon-delete"></i>删除
								</button>
							</td>
						</tr>
					`;
				});
			} else {
				html = '<tr><td colspan="8" style="text-align:center">暂无数据</td></tr>';
			}
			$('#jobGradeTable').html(html);
			
			// 重置全选框状态
			$('input[name="select-all"]').prop('checked', false);
			
			// 重新渲染所有复选框
			form.render('checkbox');
		}

		// 渲染分页
		function renderPagination(total) {
			laypage.render({
				elem: 'pagination',
				count: total,
				limit: 10,
				layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
				jump: function(obj, first) {
					if (!first) {
						// 获取当前的搜索参数
						var searchParams = {
							jobGradeCoding: $('input[name="jobGradeCoding"]').val(),
							jobGradeLevel: $('input[name="jobGradeLevel"]').val(),
							jobGradeLevelName: $('input[name="jobGradeLevelName"]').val(),
							salaryRangelower: $('input[name="salaryRangelower"]').val(),
							salaryRangelimits: $('input[name="salaryRangelimits"]').val()
						};
						loadData(obj.curr, searchParams);
					}
				}
			});
		}

		// 修改职级
		function editJobGrade(id) {
			layer.open({
				type: 2,
				title: '修改职级',
				area: ['600px', '500px'],
				content: '/JobGradeManagement/EditJobGrade?id=' + id,
				end: function() {
					loadData();
				}
			});
		}

		// 删除单个职级
		function deleteJobGrade(id) {
			layer.confirm('确定要删除该职级吗？', {
				icon: 3,
				title: '提示',
				btn: ['确定', '取消']
			}, function(index) {
				deleteJobGrades([id]);
				layer.close(index);
			});
		}

		// 获取选中的ID
		function getSelectedIds() {
			var ids = [];
			$('input[name="select-item"]:checked').each(function() {
				ids.push($(this).val());
			});
			return ids;
		}

		// 删除职级，支持单个和批量
		function deleteJobGrades(ids) {
			var token = $('input[name="__RequestVerificationToken"]').val();
			var loadingIndex = layer.load(1, {
				shade: [0.3, '#fff']
			});

			$.ajax({
				url: '/JobGradeManagement/DeleteJobGrade',
				type: 'POST',
				contentType: 'application/json',
				data: JSON.stringify(ids),
				headers: {
					'RequestVerificationToken': token,
					'X-Requested-With': 'XMLHttpRequest'
				},
				success: function(res) {
					layer.close(loadingIndex);
					if (res.success) {
						layer.msg(res.message || '删除成功', {
							icon: 1,
							time: 1000
						}, function() {
							loadData();
							// 重置全选框状态
							$('input[name="select-all"]').prop('checked', false);
							form.render('checkbox');
						});
					} else {
						layer.msg(res.message || '删除失败', {icon: 2});
					}
				},
				error: function(xhr) {
					layer.close(loadingIndex);
					var errorMsg = '删除失败';
					if (xhr.responseJSON && xhr.responseJSON.message) {
						errorMsg = xhr.responseJSON.message;
					}
					layer.msg(errorMsg, {icon: 2});
				}
			});
		}
	</script>
</body>
</html>
